import request from '@/utils/request'

// 电子书相关类型定义
export interface Ebook {
  id: number
  title: string
  description: string
  author: string
  author_id?: number
  category: EbookCategory
  format: EbookFormat
  language: string
  status: EbookStatus
  
  // 文件信息
  file_name: string
  file_size: number
  file_url: string
  file_path?: string
  
  // 书籍信息
  isbn?: string
  publisher?: string
  pages?: number
  publish_date?: string
  version?: string
  
  // 统计信息
  views: number
  downloads: number
  likes: number
  rating: number
  rating_count: number
  is_liked: boolean
  
  // 封面和预览
  cover_image?: string
  preview_url?: string
  
  // 标签
  tags?: Tag[]
  
  // 时间字段
  created_at: string
  updated_at: string
}

export interface Tag {
  id: number
  name: string
  color?: string
}

export interface User {
  id: number
  username: string
  avatar?: string
}

export interface EbookRating {
  id: number
  user_id: number
  ebook_id: number
  rating: number
  comment?: string
  user?: User
  created_at: string
  updated_at: string
}

// 电子书分类
export type EbookCategory = 
  | 'programming'    // 编程
  | 'algorithm'      // 算法
  | 'data_struct'    // 数据结构
  | 'web_dev'        // 前端开发
  | 'backend'        // 后端开发
  | 'database'       // 数据库
  | 'system'         // 系统设计
  | 'other'          // 其他

// 电子书格式
export type EbookFormat = 
  | 'pdf'            // PDF格式
  | 'epub'           // EPUB格式
  | 'mobi'           // MOBI格式
  | 'txt'            // 文本格式

// 电子书状态
export type EbookStatus = 
  | 'draft'          // 草稿
  | 'published'      // 已发布
  | 'archived'       // 已归档

// API请求参数类型
export interface GetEbooksParams {
  page?: number
  page_size?: number
  category?: EbookCategory
  format?: EbookFormat
  language?: string
  search?: string
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

export interface CreateEbookRequest {
  title: string
  description: string
  author: string
  category: EbookCategory
  format: EbookFormat
  language: string
  file_name: string
  file_size: number
  file_url: string
  file_path?: string
  isbn?: string
  publisher?: string
  pages?: number
  publish_date?: string
  version?: string
  cover_image?: string
  preview_url?: string
  tag_ids?: number[]
}

export interface UpdateEbookRequest {
  title?: string
  description?: string
  author?: string
  category?: EbookCategory
  format?: EbookFormat
  language?: string
  status?: EbookStatus
  file_name?: string
  file_size?: number
  file_url?: string
  file_path?: string
  isbn?: string
  publisher?: string
  pages?: number
  publish_date?: string
  version?: string
  cover_image?: string
  preview_url?: string
  tag_ids?: number[]
}

export interface RateEbookRequest {
  rating: number
  comment?: string
}

// API响应类型
export interface EbookListResponse {
  items: Ebook[]
  total: number
  page: number
  page_size: number
  total_pages: number
}

export interface EbookRatingListResponse {
  items: EbookRating[]
  total: number
  page: number
  page_size: number
  total_pages: number
}

export interface DownloadEbookResponse {
  download_url: string
  file_name: string
  file_size: number
}

// 电子书API类
export class EbookAPI {
  // 获取电子书列表
  static async getEbooks(params?: GetEbooksParams): Promise<EbookListResponse> {
    const response = await request.get('/v1/ebooks', { params })
    return response.data
  }

  // 获取电子书详情
  static async getEbook(id: number): Promise<Ebook> {
    const response = await request.get(`/v1/ebooks/${id}`)
    return response.data
  }

  // 创建电子书
  static async createEbook(data: CreateEbookRequest): Promise<{ id: number }> {
    const response = await request.post('/v1/ebooks', data)
    return response.data
  }

  // 更新电子书
  static async updateEbook(id: number, data: UpdateEbookRequest): Promise<{ id: number }> {
    const response = await request.put(`/v1/ebooks/${id}`, data)
    return response.data
  }

  // 删除电子书
  static async deleteEbook(id: number): Promise<void> {
    await request.delete(`/v1/ebooks/${id}`)
  }

  // 下载电子书
  static async downloadEbook(id: number): Promise<DownloadEbookResponse> {
    const response = await request.get(`/v1/ebooks/${id}/download`)
    return response.data
  }

  // 点赞/取消点赞电子书
  static async likeEbook(id: number): Promise<{ liked: boolean; likes: number }> {
    const response = await request.post(`/v1/ebooks/${id}/like`)
    return response.data
  }

  // 评分电子书
  static async rateEbook(id: number, data: RateEbookRequest): Promise<{ rating: number }> {
    const response = await request.post(`/v1/ebooks/${id}/rate`, data)
    return response.data
  }

  // 获取电子书评分列表
  static async getEbookRatings(id: number, page?: number, pageSize?: number): Promise<EbookRatingListResponse> {
    const params: any = {}
    if (page) params.page = page
    if (pageSize) params.page_size = pageSize
    
    const response = await request.get(`/v1/ebooks/${id}/ratings`, { params })
    return response.data
  }
}

// 电子书分类显示名称映射
export const EbookCategoryNames: Record<EbookCategory, string> = {
  programming: '编程',
  algorithm: '算法',
  data_struct: '数据结构',
  web_dev: '前端开发',
  backend: '后端开发',
  database: '数据库',
  system: '系统设计',
  other: '其他'
}

// 电子书格式显示名称映射
export const EbookFormatNames: Record<EbookFormat, string> = {
  pdf: 'PDF',
  epub: 'EPUB',
  mobi: 'MOBI',
  txt: 'TXT'
}

// 电子书状态显示名称映射
export const EbookStatusNames: Record<EbookStatus, string> = {
  draft: '草稿',
  published: '已发布',
  archived: '已归档'
}

// 工具函数
export const formatFileSize = (bytes: number): string => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let size = bytes
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`
}

export const getCategoryDisplayName = (category: EbookCategory): string => {
  return EbookCategoryNames[category] || '未知'
}

export const getFormatDisplayName = (format: EbookFormat): string => {
  return EbookFormatNames[format] || '未知'
}

export const getStatusDisplayName = (status: EbookStatus): string => {
  return EbookStatusNames[status] || '未知'
}
